import React, { useState, useCallback } from 'react'
import type { DragComponentData, DropPosition, DragDropConfig } from '../types'

export interface DropZoneProps {
  onDrop?: (data: DragComponentData, position: DropPosition) => void
  onDragOver?: (position: DropPosition) => void
  placeholderRenderer?: () => React.ReactNode
  config?: DragDropConfig
  children?: React.ReactNode
  className?: string
  style?: React.CSSProperties
}

export const DropZone: React.FC<DropZoneProps> = ({
  onDrop,
  onDragOver,
  placeholderRenderer,
  config,
  children,
  className,
  style
}) => {
  const [placeholderIndex, setPlaceholderIndex] = useState<number | null>(null)
  const [hoverPosition, setHoverPosition] = useState<DropPosition | null>(null)

  // 计算放置位置
  const calculateDropPosition = useCallback((e: React.DragEvent): DropPosition => {
    const rect = e.currentTarget.getBoundingClientRect()
    const x = e.clientX - rect.left
    const y = e.clientY - rect.top
    
    // 简化的索引计算逻辑 - 实际使用中可以根据需要完善
    const index = Math.round(y / 50) // 假设每个组件高度约为50px
    
    return { index, x, y }
  }, [])

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    e.dataTransfer.dropEffect = 'move'
    
    const position = calculateDropPosition(e)
    setHoverPosition(position)
    setPlaceholderIndex(position.index)
    
    onDragOver?.(position)
  }

  const handleDragLeave = () => {
    setPlaceholderIndex(null)
    setHoverPosition(null)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    
    try {
      const data = JSON.parse(e.dataTransfer.getData('text/plain'))
      const position = hoverPosition || { index: 0, x: 0, y: 0 }
      
      onDrop?.(data.sourceData, position)
    } catch (error) {
      console.error('Failed to parse drag data:', error)
    }
    
    setPlaceholderIndex(null)
    setHoverPosition(null)
  }

  // 默认占位符渲染器
  const defaultPlaceholderRenderer = () => (
    <div style={config?.styles?.placeholder || {
      width: '100%',
      height: 30,
      border: '2px dashed #1677ff',
      background: 'rgba(22,119,255,.06)',
      borderRadius: 4,
      pointerEvents: 'none'
    }} />
  )

  return (
    <div
      className={className}
      style={style || config?.styles?.dropZone}
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
    >
      {children}
      {placeholderIndex !== null && (
        <div style={{ 
          position: 'absolute', 
          top: placeholderIndex * 50, // 简化的定位
          left: 0, 
          right: 0 
        }}>
          {(placeholderRenderer || defaultPlaceholderRenderer)()}
        </div>
      )}
    </div>
  )
}